unit SmallStruct.Resource.TSSResourceTable;

interface

uses Classes,
  SmallStruct.Core,
  SmallStruct.Core.TSSObjectFactory,
  SmallStruct.Resource;

type
  TSSResourceTable = class(TSSObjectFactory, ISSResourceTable)
  private
    _ResourceRegisterTable: ISSResourceRegisterTable;
    _ResourceTable: ISSObjectContainer;
  private
    function GetResourceLoader: ISSResourceLoader;
    procedure LoadResource(AResourceName: string);
  private
    function QueryResource(AObjectName: string): ISSObjectContainer;
  public
    procedure InitObject; override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

implementation

uses Types,
  SmallStruct.Core.TSSObjectContainer,
  SmallStruct.Resource.TSSResourceRegisterTable,
  SmallStruct.BusinessObject;

{ TSSResourceTable }

constructor TSSResourceTable.Create(AOwner: TComponent);
begin
  inherited;

  _ResourceTable := TSSObjectContainer.Create(Self);
  _ResourceRegisterTable := TSSResourceRegisterTable.Create(Owner);
end;

destructor TSSResourceTable.Destroy;
begin
  _ResourceTable.ReleaseObject;
  _ResourceTable.ReleaseObjectInstance;

  _ResourceRegisterTable.ReleaseObjectInstance;

  inherited;
end;

function TSSResourceTable.GetResourceLoader: ISSResourceLoader;
begin
  Result := ((GetSystemObject.GetGlobalObjectTable as ISSObjectContainer).GetObject(SS_BUSINESS_OBJECT_FACTORY_NAME) as ISSBusinessObjectFactory).GetBusinessObject(SS_RESOURCE_LOADER_NAME) as ISSResourceLoader;
end;

procedure TSSResourceTable.InitObject;
var
  ResourceLoader: ISSResourceLoader;
begin
  inherited;

  (_ResourceRegisterTable as ISSRuntimeObject).InitObject;

  ResourceLoader := GetResourceLoader;

  try
    ResourceLoader.LoadResource(_ResourceTable);
  finally
    ResourceLoader.ReleaseObjectInstance;
  end;
end;

procedure TSSResourceTable.LoadResource(AResourceName: string);
var
  ResourceLoader: ISSResourceLoader;
begin
  ResourceLoader := GetResourceLoader;
  try
    _ResourceTable.AppendObject(AResourceName, ResourceLoader.LoadResource(AResourceName).GetObjectInstance);
  finally
    ResourceLoader.ReleaseObjectInstance;
  end;
end;

function TSSResourceTable.QueryResource(AObjectName: string): ISSObjectContainer;
var
  ResourceNameArray: TStringDynArray;
  Index: Integer;
begin
  if _ResourceRegisterTable.QueryResource(AObjectName, ResourceNameArray) then
  begin
    for Index := 0 to High(ResourceNameArray) do
      if _ResourceTable.FindObject(ResourceNameArray[Index]) <= 0 then
        LoadResource(ResourceNameArray[Index]);

    Result := TSSObjectContainer.Create(nil);

    for Index := 0 to High(ResourceNameArray) do
      Result.AppendObject(ResourceNameArray[Index], _ResourceTable.GetObject(ResourceNameArray[Index]));
  end;
end;

end.
